#!/usr/bin/env bash
#set -x
SELFDIR=$(cd $(dirname "${BASH_SOURCE[0]}");pwd)

# $1 install
# $2 <module_name>
# $3 <module_version>
function main()
{
    if [[ $# -lt 3 ]]; then
        return 1
    fi

    if [[ ! -d "${PKGREPO}" ]]; then
        echo    "The required environment variable \${PKGREPO} is missing"
        return  1
    fi

    if [[ ! -d "${DEVREPO}" ]]; then
        echo    "The required environment variable \${DEVREPO} is missing"
        return  1
    fi

    #   初始化
    source "${PKGREPO}/.share/module-install-init.bash" "$@"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    "The required environment variable \${DEVREPO} is missing"
        return  1
    fi

    #   确定主包和主包内部目录
    local majorpkg=$(cat "${MODULE_PACKAGE_DIR}/VERSION" | grep PACKAGE | grep major | awk '{print $3}')
    local innerdir=$(cat "${MODULE_PACKAGE_DIR}/VERSION" | grep PACKAGE | grep major | awk '{print $4}')

    #   备份旧软件、创建构建目录、解压主软件包
    framework backup      &&  \
    framework maketransit &&  \
    framework unzip "${MODULE_PACKAGE_DIR}/${majorpkg}" "${MODULE_TRANSIT_DIR}"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    ""
        return  1
    fi

    #   编译和安装
    local unzipdir="${MODULE_TRANSIT_DIR}/${innerdir}"
    mkdir -p    "${MODULE_INSTALL_DIR}"                         &&  \
    mv          "${unzipdir}"/*     "${MODULE_INSTALL_DIR}"     &&  \
    echo        "Build and install '${MODULE_LABEL}' success"
    RESULT=$?
    if [[ ${RESULT} -ne 0 ]]; then
        echo    "Build and install '${MODULE_LABEL}' failed(${RESULT}): '${MODULE_TRANSIT_DIR}'"
        return  1
    fi

    local proxy=$(cat "${SELFDIR}/install/proxy.ini")

    #   写 setup 文件
    touch "${MODULE_INSTALL_DIR}/setup.bash"
    echo    "export GOPROXY=\"${proxy}\""                                       >>   "${MODULE_INSTALL_DIR}/setup.bash"
    echo    "export ${MODULE_NAME_UPPER}_HOME=\"\${DEVREPO}/${MODULE_LABEL}\""  >>   "${MODULE_INSTALL_DIR}/setup.bash"
    echo    "export PATH=\${${MODULE_NAME_UPPER}_HOME}/bin:\${PATH}"            >>   "${MODULE_INSTALL_DIR}/setup.bash"
    #
    touch "${MODULE_INSTALL_DIR}/setup.csh"
    echo    "setenv GOPROXY \"${proxy}\""                                       >>   "${MODULE_INSTALL_DIR}/setup.csh"
    echo    "setenv ${MODULE_NAME_UPPER}_HOME \"\${DEVREPO}/${MODULE_LABEL}\""  >>   "${MODULE_INSTALL_DIR}/setup.csh"
    echo    "setenv PATH \${${MODULE_NAME_UPPER}_HOME}/bin:\${PATH}"            >>   "${MODULE_INSTALL_DIR}/setup.csh"

    return 0
}

main    "$@"
exit    "$?"
/e/2023-4/gitee.com/libbylg/pkgrepo